package interview;

/**
 * 启动三个线程，顺序打印ABC十次
 * User: Asuka
 * Date: 11-3-22
 * Time: 下午9:16
 */
public class PrintABCTenTimesWithThreeThreads {

    private static Character turn = 'A';
    private static Integer times = 0;

    private static class Printer implements Runnable {

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                synchronized (this) {
                    if (times == 30) {
                        Thread.currentThread().interrupt();
                        notifyAll();
                        return;
                    }
                    if (turn == 'D')
                        turn = 'A';
                    synchronized (turn) {
                        System.out.println(turn++);
                    }
                    synchronized (times) {
                        times++;
                    }
                    notifyAll();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Printer printer = new Printer();
        for (int i = 0; i < 3; i++)
            new Thread(printer).start();
    }
}
